<template>
  <el-container class="container" style="height: 100%; ">
    <el-header class="header">
      <div style="height: 50px;line-height: 50px;border-bottom: 1px solid #CCC; display: flex">
        <div style="width: 200px;padding-left: 30px;font-weight: bold;color: deepskyblue">用户界面</div>
        <div style="flex: 1"></div>
        <div style="width: 100px"></div>
        {{ user }}
      </div>
    </el-header>
    <el-container style="min-height: 100vh">
      <el-aside class="aside" style="min-height: 100%;width: 200px;">
        <el-menu
          default-active="2"
          class="el-menu-vertical-demo"
          background-color="#545c64"
          text-color="#fff"
          style="min-height: 100%"
        >
          <el-submenu index="1">
            <template slot="title">
              <i class="el-icon-location"></i>
              <span>用户功能</span>
            </template>
            <el-menu-item-group>
              <el-menu-item index="1-1" @click="CheckOrChange()">UDP报文抓取</el-menu-item>
            </el-menu-item-group>
          </el-submenu>
        </el-menu>
      </el-aside>
      <el-main class="main">
        <el-row :gutter="20">
          <el-col :span="2" style="margin-top: 10px">
            <el-label>SrcIP</el-label>
          </el-col>
          <el-col :span="3" style="margin-left: -10px">
            <el-input
              v-model="srcipScreen"
              placeholder="源地址"
              class="input-with-select"
              size="small"
              clearable>
            </el-input>
          </el-col>
          <el-col :span="2" style="margin-top: 10px">
            <el-label>DesIP</el-label>
          </el-col>
          <el-col :span="3" style="margin-left: -10px">
            <el-input
              v-model="desipScreen"
              placeholder="目的地址"
              class="input-with-select"
              size="small"
              clearable>
            </el-input>
          </el-col>
          <el-col :span="2" style="margin-top: 10px">
            <el-label>DesPort</el-label>
          </el-col>
          <el-col :span="3" style="margin-left: -10px">
            <el-input
              v-model="desportScreen"
              placeholder="目的端口号"
              class="input-with-select"
              size="small"
              clearable>
            </el-input>
          </el-col>
          <el-col :span="2" style=";margin-left: 10px">
            <el-button size="small" @click="screen()">➡️筛选</el-button>
          </el-col>
          <el-col :span="2">
            <el-button size="small" @click="start()">▶️开始</el-button>
          </el-col>
          <el-col :span="2">
            <el-button size="small" @click="stop()">⏹️停止</el-button>
          </el-col>

          <el-col :span="2">
            <el-button size="small" @click="send()">✈️发送</el-button>
          </el-col>
<!--          <el-col :span="2">-->
<!--            <el-button size="small" @click="xml()">ℹ️格式</el-button>-->
<!--          </el-col>-->
        </el-row>
        <el-table :data="showTableData" @row-dblclick="digClick">
          <el-table-column prop="packet.sec" label="Time" width="160">
          </el-table-column>
          <el-table-column prop="packet.dst_port" label="port" width="160">
          </el-table-column>
          <el-table-column prop="packet.src_ip" label="Source" width="160">
          </el-table-column>
          <el-table-column prop="packet.dst_ip" label="Destination" width="160">
          </el-table-column>
          <el-table-column prop="" label="Protocol" width="160">
            udp
          </el-table-column>
          <el-table-column prop="packet.len" label="Length" width="160">
          </el-table-column>
          <el-table-column prop="packet.version" label="Version">
          </el-table-column>
          <el-table-column label="xml查看">
            <template v-slot="scope">
              <el-button type="success" @click="exportXML(scope.row)">xml</el-button>
            </template>
          </el-table-column>
          <el-table-column label="日志查看">
            <el-button type="primary" @click="log()">日志</el-button>
          </el-table-column>
        </el-table>
        <el-dialog title="分组显示" :visible.sync="diaUDPVisible" @close="handleGroupClose">
          <el-row class="row-bg" :gutter="20">
            <el-col :span="15">
              <div class="grid-content bg-purple"/>
              <el-card class="box-card">
                <el-collapse v-model="activeNames" @change="handleChange">
                  <el-collapse-item
                    :title="'Internet Protocol version '+packet.version+', Src: '+packet.src_ip+', Dst: '+packet.dst_ip"
                    name="2">
                  </el-collapse-item>
                  <el-collapse-item
                    :title="'User Datagram Protocol '+', Src Port: '+packet.src_port+', Dst Port: '+packet.dst_port"
                    name="3">
                    <el-card class="box-card">
                      <div>
                        Scource Port: {{ packet.src_port }}
                        <br>
                        Destination Port: {{ packet.dst_port }}
                        <br>
                        Length: {{ packet.len }}
                        <br>
                      </div>
                    </el-card>
                  </el-collapse-item>

                  <el-collapse-item :title="'Data ('+packet.len+' bytes) '" name="4">
                    <div>
                      Data: {{ this.mydata }}
                      <br>
                      [Length:{{ packet.len }}]
                    </div>
                  </el-collapse-item>
                </el-collapse>
              </el-card>
              <br>
              <el-row :gutter="30">
                <el-col :span="12">
                  <el-card class="box-card">
                    <span v-for="(i,index) in raw" :key="index">
                      {{ i }}
                    </span>
                  </el-card>
                </el-col>
                <el-col :span="12">
                  <el-card class="box-card" shadow="hover">
                    <span v-for="(i,index) in intraw" :key="index">
                      {{ i }}
                    </span>
                  </el-card>
                </el-col>
              </el-row>
            </el-col>
            <el-col :span="9">
              <div class="grid-content bg-purple-light"/>
              <el-card class="box-card">
                <el-input
                  v-model="textarea"
                  :rows="2"
                  type="textarea"
                  placeholder="Please input"
                  :value="xmltext"
                  />
              </el-card>
              <el-card class="box-card">
                <el-table
                  :data="decodeData"
                  style="width: 100%">
                  <el-table-column
                    prop="key"
                    label="key"
                    width="100">
                  </el-table-column>
                  <el-table-column
                    prop="value"
                    label="value"
                    width="100">
                  </el-table-column>
                  <el-table-column
                    prop="expect"
                    label="expect"
                    width="100">
                  </el-table-column>
                </el-table>
                
              </el-card>
              <el-button @click="decode()">解码</el-button>
            </el-col>
          </el-row>
        </el-dialog>
      </el-main>
      <el-dialog title="UDP报文发送" :visible.sync="dialogFormVisible">
        <el-input style="margin: 10px" v-model="form.destination" autocomplete="off"
                  placeholder="Destination IP"></el-input>
        <el-input style="margin: 10px" v-model="form.port" autocomplete="off"
                  placeholder="Port"></el-input>
        <!-- <el-input style="margin: 10px" v-model="text" autocomplete="on" :autosize="{ minRows: 4, maxRows: 4 }"
                  type="textarea"
                  placeholder="content" v-if="textVisible"></el-input> -->
        <el-input style="margin: 10px" v-model="xmltext" autocomplete="on" :autosize="{ minRows: 4, maxRows: 4 }"
                  type="textarea"
                  placeholder="XML格式定义" v-if="textVisible"></el-input>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogFormVisible = false">Cancel</el-button>
            <el-button type="primary" @click="sendinfo()"
            >Send</el-button>
          </span>
        </template>
      </el-dialog>
      <el-dialog title="XML格式定义" :visible.sync="diaXMLVisible">
      </el-dialog>
    </el-container>
  </el-container>

</template>

<script>

  import x2js from 'x2js'
  import {Encode, Decode} from "../assets/util";

  export default {
    mounted() {
      this.timer = setInterval(() => {
        // console.log("开始")
        this.filter()
      }, 5000)
    },
    beforeDestroy() {
      this.$once('hook:beforeDestroy', () => {
        clearInterval(this.timer)
      })
    },
    data() {
      return {
        srcipScreen: '',
        desipScreen: '',
        desportScreen: '',
        raw: [],
        decodetxt: "",
        input: "",
        diaUDPVisible: false,
        tableData: [],
        decodeData: [],
        showTableData: [],
        mydata: '',
        ip: '',
        timer: null,
        packet: '',
        datalink: '',
        intraw: [],
        myraw: [],
        xmltext: '<root>\n<encode>unicode</encode>\n<data>\n\t<Field name="" value=""/>\n</data>\n</root>',
        seq: this.$route.query.seq,
        name: this.$route.query.name,
        dialogFormVisible: false,
        diaXMLVisible: false,
        user: sessionStorage.getItem('userid'),
        gridData: [],
        tablemember: [],
        activeNames: '',
        activeName: '',
        textVisible: true,
        fileVisible: false,
        textarea: '<root>\n<encode>unicode</encode>\n<data>\n\t<Field name="" value=""/>\n</data>\n</root>',
        text: '',
        file: '',
        js: null,
        form: {
          destination: '',
          content: '',
          port: '',
        },
        type: 1,
      }
    },
    name: "Home",
    methods: {
      start() {
        this.showTableData.length = 0
        this.tableData.length = 0
        this.showTableData = []
        this.showTableData = []
        this.timer = setInterval(() => {
          // console.log("开始")
          this.filter()
        }, 5000)
      },
      stop() {
        clearInterval(this.timer)
      },
      digClick(row) {
        // console.log(row)
        this.ip = row
        this.raw = []
        this.intraw = []
        this.myraw = []
        let i = 0
        while (i < row.raw.length) {
          this.raw.push(row.raw[i].toString(16))
          this.intraw.push(row.raw[i] > 127 ? '.' : String.fromCharCode(row.raw[i]))
          i = i + 1
        }
        this.mydata = ''
        let j = 28
        while (j < row.raw.length) {
          this.mydata = this.mydata + String.fromCharCode(row.raw[j])
          this.myraw.push(row.raw[j])
          j = j + 1
        }
        this.packet = this.ip.packet
        this.datalink = this.packet.datalink
        this.diaUDPVisible = true
      },
      send() {
        this.dialogFormVisible = true
      },
      decode() {
        this.XMLtoJson(this.textarea)
        console.log(this.js.root.encode, this.myraw)
        this.decodetxt = Decode(this.js.root.encode, this.myraw)
        var recieveJS = JSON.parse(this.decodetxt)
        console.log('recieveJs:',recieveJS)
        console.log('this.js.field:',this.js.root.data.Field)

        this.decodeData = []
        for(let i in this.js.root.data.Field) {
          for(let j in recieveJS.Field) {
            if(this.js.root.data.Field[i]._name == recieveJS.Field[j]._name) {
              this.decodeData.push({
                key: recieveJS.Field[j]._name,
                value: recieveJS.Field[j]._value,
                expect: this.js.root.data.Field[i]._value
              })
              console.log(recieveJS.Field[j]._name)
            }
          }
        }
      },
      filter() {
        this.$http({
            url: "cp/shark",
            method: "post"
          }
        ).then((response) => {
          console.log(response);
          for (let i in response.data) {
            this.tableData.push(response.data[i])
            let access = true;
            if(this.srcipScreen != '' && this.srcipScreen != this.tableData[i].packet.src_ip) {
              access = false
            }
            if(this.desipScreen != '' && this.desipScreen != this.tableData[i].packet.dst_ip) {
              access = false
            }
            if(this.desportScreen != '' && this.desportScreen != this.tableData[i].packet.dst_port) {
              access = false
            }
            if(access) {
              this.showTableData.push(this.tableData[i])
            }
            // if(this.desport == null or this.desport == )
          }
          // console.log(this.tableData)
        })
      },
      handleChange(val) {
        console.log(val)
      },
      handleChange1(val) {
        console.log(val)
      },
      getfile(file) {
        // console.log(file);
        var reader = new FileReader();
        reader.readAsDataURL(file.raw); // 一定要传入file格式
        reader.onload = () => {
          // console.log("file 转 base64结果：" + reader.result);
          this.file = reader.result
          // console.log(this.file)
        };
        reader.onerror = function (error) {
          console.log("Error: ", error);
        };
      },
      selectChanged() {
        // console.log(this.type)
        if (this.type === 1) {
          this.textVisible = false
          this.fileVisible = false
        } else if (this.type === 2) {
          this.textVisible = true
          this.fileVisible = false
        } else if (this.type === 3) {
          this.textVisible = false
          this.fileVisible = true
        }
      },
      sendinfo() {
        this.XMLtoJson(this.xmltext)
        console.log(this.js)
        // this.form.content = Encode(this.js.encode, this.text)
        this.form.content = Encode(this.js.root.encode, JSON.stringify(this.js.root.data))
        // console.log(this.form.content)
        this.dialogFormVisible = false

        let param = new FormData()
        param.append('address', this.form.destination)
        param.append('port', this.form.port)
        param.append('content', this.form.content)

        this.$http({
          url: "cp/send",
          data: param,
          method: "post"
        })
      },
      exportXML(row) {
        // console.log(row)
        let x = new x2js()
        let obj = {
          Info: row.packet,
        };
        let xml = x.js2xml(obj);
        let url = window.URL.createObjectURL(
          new Blob([xml], {type: "text/xml"})
        );
        let link = document.createElement("a");
        link.style.display = "none";
        link.href = url;
        link.setAttribute("download", "UDP报文");
        document.body.appendChild(link);
        link.click();
      },
      log() {
        this.$http({
            url: "cp/log",
            method: "get"
          }
        ).then((response) => {
          // console.log(response);
          let log = response.data
          let url = window.URL.createObjectURL(
            new Blob([log], {type: "text/log"})
          );
          let link = document.createElement("a");
          link.style.display = "none";
          link.href = url;
          link.setAttribute("download", response.headers['file-name']);
          document.body.appendChild(link);
          link.click();
        })
      },
      xml() {
        this.diaXMLVisible = true
      },
      XMLtoJson(txt) {
        console.log(txt)
        var xml = txt
        var x = new x2js()
        this.js = x.xml2js(xml)
        // console.log(this.js)
      },
      handleGroupClose() {
        this.textarea = ''
        this.decodetxt = ''
      },
      screen() {
        this.showTableData = []
        for(let i in this.tableData) {
          let access = true;
          if(this.srcipScreen != '' && this.srcipScreen != this.tableData[i].packet.src_ip) {
            access = false
          }
          if(this.desipScreen != '' && this.desipScreen != this.tableData[i].packet.dst_ip) {
            access = false
          }
          if(this.desportScreen != '' && this.desportScreen != this.tableData[i].packet.dst_port) {
            access = false
          }
          if(access) {
            this.showTableData.push(this.tableData[i])
          }
        }

      }
    },
  }
</script>
<style scoped>
  .container {
    height: 100%;
    font-size: 15px;
  }

  .main_header {
    display: flex;
    align-content: center;
    justify-content: space-between;
    padding: 0 15px;
    box-sizing: border-box;
  }

</style>
